package com.sneakxy.mybatis.commons.repository.query.domain.criterions;

import java.util.List;

import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.scripting.xmltags.StaticTextSqlNode;
import org.apache.ibatis.session.Configuration;

import com.sneakxy.mybatis.commons.dialect.Dialect;
import com.sneakxy.mybatis.commons.orm.mapping.MybatisColumn;

/**
 * @author 潜行的青衣
 */
public class NullableCriterion extends AbstractCriterion {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4743335248460136355L;

	/**
	 * @param domainClass
	 * @param property
	 * @param nullable
	 */
	public NullableCriterion(Class<?> domainClass, String property, boolean nullable) {
		super(domainClass, property, nullable);
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybatis.commons.repository.query.domain.Criterion#toSql(java.lang.String)
	 */
	@Override
	public SqlNode toSql(Configuration config, String operator, String parameterName) {
		Dialect dialect = this.getDialect(config);
		Boolean nullable = (Boolean) this.getValue();
		List<MybatisColumn> columns = this.getColumns(config.getTypeHandlerRegistry(), parameterName);
		MybatisColumn column = columns.get(0);
		StringBuilder sqlBuilder = new StringBuilder();
		sqlBuilder.append(operator).append(" ").append(getOpen());
		sqlBuilder.append(dialect.formatColumnName(column.getColumn())).append(" ");
		sqlBuilder.append(nullable ? "IS NULL" : "IS NOT NULL").append(getClose()).append(" ");
		return new StaticTextSqlNode(sqlBuilder.toString());
	}

}
